#导入模块
import cv2 as cv
import os
import time
path = "data/my-train"
if not os.path.exists(path):
    os.makedirs(path)

def face_detect_demo(img):
    #将图片转换为灰度图片
    gray=cv.cvtColor(img,cv.COLOR_BGR2GRAY)
    #加载特征数据
    face_detector=cv.CascadeClassifier('data/haarcascade_frontalface_default.xml')
    faces=face_detector.detectMultiScale(gray)
    for x,y,w,h in faces:
        cv.rectangle(img,(x,y),(x+w,y+h),color=(0,255,0),thickness=2)
        # cv.circle(img,center=(x+w//2, y+h//2),radius=w//2, color=(0,255,255), thickness=2)
    cv.imshow('result',img)

#获取摄像头
cap=cv.VideoCapture(0)
num=0 #图片编号

while True:
    flag,frame=cap.read()
    print('flag:',flag,'frame.shape:',frame.shape)
    if not flag:
        break
    # 检测按键，使用一个标志变量来记录按键状态，防止多次保存同一张图片
    key = cv.waitKey(1) & 0xFF
    if key == ord('s'):
        cv.imwrite(f"{path}/{num}.jpg", frame)
        num += 1
        print(f"保存图片 {num}.jpg")
    face_detect_demo(frame)
    if key == ord('q'):
        break

cv.destroyAllWindows()
cap.release()
